﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
using System.Net.Mail;
using System.Net.Security;
using System.Net.NetworkInformation;
using QLTV_V2.BussinessLogic;
using QLTV_V2.BussinessObject;
using QLTV_V2.DataAccess;

namespace QLTV_V2
{
    public partial class FrmGuiMail : DevComponents.DotNetBar.Office2007RibbonForm
    {
        public FrmGuiMail()
        {
            InitializeComponent();
        }
        ConnectData conn = new ConnectData();
        TcpClient tcp;
        SslStream netStream;
        StreamReader rd;
        string read;
        bool checkSend = true;
        byte[] write;
        System.Text.ASCIIEncoding enc;
        string from, pass, to, bcc, sub, body;
        private void FrmGuiMail_Load(object sender, EventArgs e)
        {
            string sql = "select distinct b.MaMuonTra,a.MaBanDoc, TenBanDoc,count(MaCTMuonTra)as SoLuongSach, NgayMuon, NgayPhaiTra,Email " +
               "from BanDoc a join PhieuMuonTra b on a.MaBanDoc=b.MaBanDoc " +
               "join CTMuonTra c on b.MaMuonTra=c.MaMuonTra " +
               " where (NgayTra is not null and NgayTra>NgayPhaiTra) or (NgayTra is null and NgayPhaiTra<GETDATE()) " +
               "group by b.MaMuonTra,a.MaBanDoc, TenBanDoc,NgayMuon, NgayPhaiTra,Email ";
               
            dgv_HetHan.DataSource = conn.GetDataTable(sql);
        }

        private void btn_Send_Click(object sender, EventArgs e)
        {   
            int dem=0;
            for (int i = 0; i < dgv_HetHan.Rows.Count - 1; i++)
                if (Convert.ToBoolean(dgv_HetHan.Rows[i].Cells["chon"].Value) == true)
                    dem++;
            prgMail.Maximum = dem;
            prgMail.Minimum = 0;
            prgMail.Step = 1;
            //
            int c = dgv_HetHan.Rows.Count - 1;
            dgv_HetHan.CurrentCell = dgv_HetHan.Rows[c].Cells[0];
            dgv_HetHan.CurrentCell = dgv_HetHan.Rows[0].Cells[0];

            for (int i = 0; i < dgv_HetHan.Rows.Count - 1; i++)
            {
                if (Convert.ToBoolean(dgv_HetHan.Rows[i].Cells["chon"].Value) == true)
                {
                    string sql = "select * from Email";
                    DataRow dr = conn.GetDataTable(sql).Rows[0];
                    from = dr["nameMail"].ToString();
                    pass = dr["passMail"].ToString();
                    to = dgv_HetHan.Rows[i].Cells["Email"].Value.ToString();
                    //to = "tienhoaqng@gmail.com";
                    bcc = dr["bccName"].ToString();
                    sub = dr["Title"].ToString();
                    body = dr["Contents"].ToString();
                    sendEmail(from, pass, to, bcc, sub, body);

                    if (checkSend == true)//Gưi thành công
                    {
                        prgMail.PerformStep();
                        MessageBox.Show("Đã gửi!");
                    }
                }
            }
            prgMail.Value = dem;
        }
        //Check internet
        private bool checkInternet()
        {
            Ping p = new Ping();
            try
            {
                PingReply pr = p.Send("google.com.vn", 3000);
                if (pr.Status == IPStatus.Success)
                    return true;
            }
            catch
            {

            }
            return false;
        }
        //Check mail
        private bool checkMail(string Email, string Pass)
        {
            string mail = Email.Substring(Email.LastIndexOf("@") + 1);
            string host = null;
            int port = 0;
            switch (mail)
            {
                case "gmail.com": host = "pop.gmail.com"; port = 995; break;
                case "hotmail.com": host = "pop3.live.com"; port = 995; break;
                case "yahoo.com": host = "pop.mail.yahoo.com"; port = 465; break;
                case "yahoo.com.vn": host = "pop.mail.yahoo.com.vn"; port = 995; break;
            }
            //Connect mail server
            tcp = new TcpClient();
            tcp.Connect(host, port);
            netStream = new SslStream(tcp.GetStream());
            netStream.AuthenticateAsClient(host);
            rd = new StreamReader(netStream);
            //Check user and password
            read = null;
            write = new byte[1024];
            enc = new System.Text.ASCIIEncoding();
            rd.ReadLine();
            write = enc.GetBytes("USER " + Email + "\r\n");
            netStream.Write(write, 0, write.Length);
            netStream.Flush();
            read = rd.ReadLine();
            write = enc.GetBytes("PASS " + Pass + "\r\n");
            netStream.Write(write, 0, write.Length);
            netStream.Flush();
            read = rd.ReadLine();
            if (!read.StartsWith("+OK"))
                return false;
            return true;
        }
        //Send mail
        private void sendEmail(string From, string Pass, string To, string BCC, string Subject, string Body)
        {
            if (checkInternet())
            {
                if (checkMail(From, Pass))
                {
                    try
                    {
                        MailMessage mail = new MailMessage();
                        mail.From = new MailAddress(From, "Trung tâm thông tin tư liệu Trường CĐ CNTT Hữu nghị Việt - Hàn", Encoding.UTF8);
                        mail.To.Add(To);
                        if (!string.IsNullOrEmpty(BCC))
                        mail.Bcc.Add(BCC);
                        mail.Subject = Subject;
                        mail.SubjectEncoding = Encoding.UTF8;
                        mail.Body = Body;
                        mail.BodyEncoding = Encoding.UTF8;
                        mail.Priority = MailPriority.High;
                        string email = From.Substring(From.LastIndexOf("@") + 1);

                        SmtpClient smtp = new SmtpClient();
                        switch (email)
                        {
                            case "gmail.com": smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; break;
                            case "hotmail.com": smtp.Host = "smtp.live.com"; smtp.Port = 587; smtp.EnableSsl = true; break;
                            case "yahoo.com": smtp.Host = "smtp.mail.yahoo.com"; smtp.Port = 995; smtp.EnableSsl = false; break;
                            case "yahoo.com.vn": smtp.Host = "smtp.mail.yahoo.com.vn"; smtp.Port = 25; smtp.EnableSsl = false; break;
                        }
                        smtp.Credentials = new System.Net.NetworkCredential(From, Pass);
                        smtp.Send(mail);
                        checkSend = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
                else
                    MessageBox.Show("Tên đăng nhập hoặc tài khoản không đúng!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
                MessageBox.Show("Không có kết nối Internet!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            quitEmail();
        }

        private void quitEmail()
        {
            write = enc.GetBytes("QUIT\r\n");
            netStream.Write(write, 0, write.Length);
        }

        private void btn_Thoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_Tuychinh_Click(object sender, EventArgs e)
        {
            FrmCauHinhMail frm = new FrmCauHinhMail();
            frm.ShowDialog();
        }
        private void btn_ChonHet_Click(object sender, EventArgs e)
        {
            int count = dgv_HetHan.Rows.Count - 1;
            for (int i = 0; i < count; i++)
                dgv_HetHan.Rows[i].Cells["chon"].Value = true;
        }

        private void btn_BoChon_Click(object sender, EventArgs e)
        {
            int count = dgv_HetHan.Rows.Count - 1;
            for (int i = 0; i < count; i++)
                dgv_HetHan.Rows[i].Cells["chon"].Value = false;
        }

    }
}
